﻿using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.db.Models.Terminal;
using EntityFramework.Extensions;
using george.Data;
using System;
using System.ComponentModel;
using System.Linq;
using com.nm.Attributes;
using com.nm.Helper;
using TerminalAPI.models;

namespace TerminalAPI
{
    [Description("货架陈列的增删改查")]
    public class DisplayShelfHandler : BaseHandler
    {
        [MustLogin]
        [Description("货架陈列列表")]
        [ReturnType(typeof(PaperData<ShelfDispalyModel.ListModel>))]
        public ApiResult GetList(
            [ParamDescription("关键字")] string Keys = "",
            [ParamDescription("年份")] string Year = "",
            [ParamDescription("季节")] string Season = "",
            [ParamDescription("删除标识")] int IsRemove = -1,
            [ParamDescription("页码")]int Page = 1,
            [ParamDescription("页数")]int Size = 10)
        {
            var dc = new TerminalEntities();
            var query = (from shop in dc.Tm_ShelfDisplay
                         join good in dc.Tm_GoodShelf on shop.GSID equals good.GSID
                         select new
                         {
                             shop,
                             good.GSCode,
                             good.GSName,
                             good.IsRemove,
                             details = (from g in dc.Tm_ShelfDisplayDetail where g.SDID == shop.SDID select g).ToList()
                         });
            if (!string.IsNullOrWhiteSpace(Keys))
                query = query.Where(t => t.GSCode.Contains(Keys)
                || t.GSName.Contains(Keys));
            if (!string.IsNullOrWhiteSpace(Year))
                query = query.Where(t => t.shop.Year.Contains(Year));
            if (!string.IsNullOrWhiteSpace(Season))
                query = query.Where(t => t.shop.Season.Contains(Season));
            if (IsRemove == 0)
            {
                query = query.Where(r => r.IsRemove == false);
            }
            else if (IsRemove == 1)
            {
                query = query.Where(r => r.IsRemove == true);
            }
            var result = PaperData<ShelfDispalyModel.ListModel>.Create(query.Count(), Size, Page);
            result.Items = query.OrderByDescending(t => t.shop.CreateDate).ToList().Skip(result.Skip).Take(result.Limt)
                .Select(o => new ShelfDispalyModel.ListModel
                {
                    ASKC = o.shop.ASKC,
                    BSKC = o.shop.BSKC,
                    CSKC = o.shop.CSKC,
                    CreateDate = o.shop.CreateDate,
                    Season = o.shop.Season,
                    IsRemove = o.shop.IsRemove,
                    SDID = o.shop.SDID,
                    Year = o.shop.Year,
                    GSCode = o.GSCode,
                    GSName = o.GSName,
                    GSID = o.shop.GSID,
                    ImageUrl = ImageHelper.GetResolveImageUrl(o.GSCode,"good", "http"),
                    GoodDetails = o.details.ToList().Select(g => new ShelfDispalyModel.CreateDetailModel
                    {
                        Series = g.Series,
                        CommodityLayer = g.CommodityLayer,
                        Category=g.Category,
                        Memo = g.Memo,
                        Maximum = g.Maximum,
                        Minimum = g.Minimum,
                        Avgximum = g.Avgximum,
                        SDDID = g.SDDID
                    }).ToList()
                }).ToList();
            return Success(result);
        }

        [MustLogin]
        [Description("货架陈列明细")]
        [ReturnType(typeof(ShelfDispalyModel.ListModel))]
        public ApiResult GetID(
            [ParamDescription("ID")] int ID)
        {
            var dc = new TerminalEntities();
            var query = (from shop in dc.Tm_ShelfDisplay
                         join good in dc.Tm_GoodShelf on shop.GSID equals good.GSID
                         where shop.SDID == ID
                         select new
                         {
                             shop,
                             good.GSCode,
                             good.GSName,
                             details = (from g in dc.Tm_ShelfDisplayDetail where g.SDID == shop.SDID select g).ToList()
                         }).FirstOrDefault();

            var result = new ShelfDispalyModel.ListModel
            {
                ASKC = query.shop.ASKC,
                BSKC = query.shop.BSKC,
                CSKC = query.shop.CSKC,
                CreateDate = query.shop.CreateDate,
                Season = query.shop.Season,
                IsRemove = query.shop.IsRemove,
                SDID = query.shop.SDID,
                Year = query.shop.Year,
                GSCode = query.GSCode,
                GSName = query.GSName,
                GSID = query.shop.GSID,
                ImageUrl = ImageHelper.GetResolveImageUrl(query.GSCode,"good", "http"),
                GoodDetails = query.details.ToList().Select(g => new ShelfDispalyModel.CreateDetailModel
                {
                    Series = g.Series,
                    CommodityLayer = g.CommodityLayer,
                    Category = g.Category,
                    Memo = g.Memo,
                    Maximum = g.Maximum,
                    Minimum = g.Minimum,
                    Avgximum = g.Avgximum,
                    SDDID = g.SDDID
                }).ToList()
            };
            return Success(result);
        }

        [JsonType]
        [MustLogin]
        [Description("新增货架陈列信息")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Create([ParamDescription("输入参数")]ShelfDispalyModel.CreateModel param)
        {
            if (string.IsNullOrWhiteSpace(param.Year)) return Error("年份不能为空");
            if (string.IsNullOrWhiteSpace(param.Season)) return Error("季节不能为空");
            if (param.ASKC < 0) return Error("A级陈列标准SKC不能小于零");
            if (param.BSKC < 0) return Error("B级陈列标准SKC不能小于零");
            if (param.CSKC < 0) return Error("C级陈列标准SKC不能小于零");
            if (param.GSID == 0) return Error("货架编号不能为零");
            if (param.GoodDetails == null || param.GoodDetails.Count == 0) return Error("陈列明细不能为空");
            var dc = new TerminalEntities();
            if (dc.Tm_ShelfDisplay.Any(t => t.GSID == param.GSID)) return Error("货架信息已存在");
            var tran = dc.Database.BeginTransaction();
            var shelf = new Tm_ShelfDisplay
            {
                ASKC = param.ASKC,
                BSKC = param.BSKC,
                CSKC = param.CSKC,
                CreateDate = DateTime.Now,
                GSID = param.GSID,
                IsRemove = false,
                ModifyDate = DateTime.Now,
                Operator = this.UserId,
                Season = param.Season,
                Year = param.Year
            };
            dc.Tm_ShelfDisplay.Add(shelf);

            #region 陈列明细
            foreach (var item in param.GoodDetails)
            {
                var goods = new Tm_ShelfDisplayDetail
                {
                    Series = item.Series,
                    SDID = shelf.SDID,
                    CommodityLayer = item.CommodityLayer,
                    Category=item.Category,
                    Avgximum = item.Avgximum,
                    Maximum = item.Maximum,
                    Minimum = item.Minimum,
                    Memo = item.Memo
                };
                dc.Tm_ShelfDisplayDetail.Add(goods);
            }
            #endregion
            try
            {
                dc.SaveChanges();
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return Error(ex.Message);
            }
            return Success(0);
        }

        [JsonType]
        [MustLogin]
        [Description("编辑货架陈列信息")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Modify([ParamDescription("输入参数")]ShelfDispalyModel.ModifyModel param)
        {
            if (string.IsNullOrWhiteSpace(param.Year)) return Error("年份不能为空");
            if (string.IsNullOrWhiteSpace(param.Season)) return Error("季节不能为空");
            if (param.ASKC < 0) return Error("A级陈列标准SKC不能小于零");
            if (param.BSKC < 0) return Error("B级陈列标准SKC不能小于零");
            if (param.CSKC < 0) return Error("C级陈列标准SKC不能小于零");
            if (param.GSID == 0) return Error("货架编号不能为零");
            if (param.GoodDetails == null || param.GoodDetails.Count == 0) return Error("陈列明细不能为空");
            var dc = new TerminalEntities();
            if (dc.Tm_ShelfDisplay.Any(t => t.GSID == param.GSID && t.SDID != param.SDID)) return Error("货架信息已存在");
            var tran = dc.Database.BeginTransaction();
            var query = dc.Tm_ShelfDisplay.FirstOrDefault(t => t.SDID == param.SDID);
            if (query == null) return Error("无数据");
            query.ASKC = param.ASKC;
            query.BSKC = param.BSKC;
            query.CSKC = param.CSKC;
            query.GSID = param.GSID;
            query.ModifyDate = DateTime.Now;
            query.Operator = this.UserId;
            query.Season = param.Season;
            query.Year = param.Year;
            
            #region 陈列明细
            if (param.GoodDetails.Count > 0)
            {
                dc.Tm_ShelfDisplayDetail.Where(t => t.SDID == query.SDID).Delete();
                foreach (var item in param.GoodDetails)
                {
                    var style = new Tm_ShelfDisplayDetail
                    {
                        Series = item.Series,
                        SDID = query.SDID,
                        CommodityLayer = item.CommodityLayer,
                        Category=item.Category,
                        Minimum = item.Minimum,
                        Maximum = item.Maximum,
                        Avgximum = item.Avgximum,
                        Memo = item.Memo
                    };
                    dc.Tm_ShelfDisplayDetail.Add(style);
                }
            }
            #endregion
            try
            {
                dc.SaveChanges();
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return Error(ex.Message);
            }
            return Success(0);
        }

        [MustLogin]
        [ReturnType(typeof(int), "0-成功")]
        [Description("删除陈列信息")]
        public ApiResult Remove([ParamDescription("货架陈列ID")]int SDID)
        {
            var dc = new TerminalEntities();
            //dc.Tm_ShelfDisplayDetail.Where(t => t.SDID == SDID).Delete();
            //dc.Tm_ShelfDisplay.Where(t => t.SDID == SDID).Delete();
            var query = dc.Tm_ShelfDisplay.FirstOrDefault(t=>t.SDID==SDID);
            if (query == null) return Error("无数据");
            query.IsRemove = true;
            try
            {
                dc.SaveChanges();
            }
            catch(Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }
    }
}
